package cn.itcast.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class CacheIntercepter implements HandlerInterceptor {
    @Value("${health.cache.enable}")
    private Boolean enable;
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //缓存全局开关校验
        //开启就放行
        if(!enable){
            return true;
        }
        //判断是不是handler方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //判断是否是@cache
        if(!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)){
            return true;
        }
        String redisKey = createRedisKey(request);
        String value = redisTemplate.opsForValue().get(redisKey);
        System.out.println(value);
        //判断取出的值是否为空
        if(value == null){
            return true;
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(value);
        return false;
    }

    public static String createRedisKey(HttpServletRequest request) {
        String requestURI = request.getRequestURI();//请求路径
        String queryString = request.getQueryString();//请求参数
        String token = request.getHeader("Autoorization");//token
        String md5Hex = DigestUtils.md5Hex(requestURI + "@" + queryString + "@" + token);
        return "health@"+md5Hex;
    }
}
